package com.zhs.elasticsearch.util;

import org.apache.commons.io.IOUtils;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * es加载脚本工具类
 * @Author zhenghuisheng
 * @Date 2024/12/28 17:01
 */
public class EsScriptUtils {
    private static final Map<String, String> SCRIPT_CACHE = new ConcurrentHashMap<>();

    private static String getCacheScript(String name) {
        return SCRIPT_CACHE.computeIfAbsent(name, key -> {
            try {
                return IOUtils.toString(Objects.requireNonNull(EsScriptUtils.class.getResourceAsStream("/es_script/" + name)), StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        });
    }

    public static Script buildScript(String name, Map<String, Object> params) {
        String cacheScript = getCacheScript(name);
        return new Script(ScriptType.INLINE, Script.DEFAULT_SCRIPT_LANG, cacheScript, params);
    }
}
